import React, { useState, useEffect, useCallback } from 'react'
import { useHistory } from 'react-router-dom'
import { putAccWorkAddWork } from '../../../../financialApi'
import { getSysDepartmentFindList, getSysUserSelected } from '../../../../../../Api/listUrl'
import { Button, Form, Input, InputNumber, message, Col, Row, Space, Select } from 'antd'
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons'

const { TextArea } = Input;
const { Option } = Select;

/**
 * @description: 财务-办公费用
 * @author: xiaoxujs
 * @upDate: xiaoxujs（2021-07-07）
 */

const WordOffice = () => {
    const history = useHistory()
    const [buttonLoading, setButtonLoading] = useState(false)
    const [allMoney, setAllMoney] = useState([])
    const [allMoneyData, setAllMoneyData] = useState([])
    const [departmentList, setDepartmentList] = useState([])
    const [userList, setUserList] = useState([])
    const userFun = useCallback(
        () => {
            (async () => {
                const { code, msg, data } = await getSysUserSelected()
                if (code === '20000') {
                    setUserList(data)
                } else {
                    message.error(msg)
                }
            })()
        },
        [],
    )
    const departmentFun = useCallback(
        () => {
            (async () => {
                const { code, msg, data } = await getSysDepartmentFindList()
                if (code === '20000') {
                    setDepartmentList(data)
                } else {
                    message.error(msg)
                }
            })()
        },
        [],
    )
    useEffect(() => {
        departmentFun()
        userFun()
    }, [departmentFun, userFun])

    const onFinish = (values) => {
        ; (async () => {
            setButtonLoading(true)
            const { code, msg } = await putAccWorkAddWork(values)
            if (code === '20000') {
                message.success('提交成功')
                setButtonLoading(false)
                history.go('-1')
            } else {
                setButtonLoading(false)
                message.error(msg)
            }
        })()
    };
    //获取数量
    const handleNumber = (value, key) => {
        let newArray = [...allMoneyData];
        let allMoneyNewArray = [...allMoney];
        if (!newArray[key]) {
            newArray[key] = {
                price: 0,
                itemCount: value
            }
        }
        newArray[key].itemCount = value;
        allMoneyNewArray[key] = value * newArray[key].price;
        setAllMoney(allMoneyNewArray);
        setAllMoneyData(newArray);
    };
    //获取单价
    const handlePrice = (value, key) => {
        let newArray = [...allMoneyData];
        let allMoneyNewArray = [...allMoney];
        if (!newArray[key]) {
            newArray[key] = {
                price: value,
                itemCount: 0
            }
        }
        newArray[key].price = value;
        allMoneyNewArray[key] = value * newArray[key].itemCount;
        setAllMoney(allMoneyNewArray);
        setAllMoneyData(newArray);
    };
    return <Form
        labelCol={{ span: 3 }}
        wrapperCol={{ span: 16 }}
        onFinish={onFinish}
    >
        <Form.Item
            label="申请人"
            name="applicant"
            rules={[{ required: true, message: '请选择申请人!' }]}
        >
            <Select>
                {
                    userList.map(item => <Option value={item.id} key={item.id}>{item.name}</Option>)
                }
            </Select>
        </Form.Item>
        <Form.Item
            label="部门主管"
            name="director"
            rules={[{ required: true, message: '请选择部门主管!' }]}
        >
            <Select>
                {
                    userList.map(item => <Option value={item.id} key={item.id}>{item.name}</Option>)
                }
            </Select>
        </Form.Item>
        <Form.Item
            label="申请事由"
            name="matter"
            rules={[{ required: true, message: '请输入申请事由!' }]}
        >
            <TextArea />
        </Form.Item>
        <Form.Item
            label="借款金额（元）"
            name="money"
            rules={[{ required: true, message: '请输入借款金额!' }]}
        >
            <InputNumber />
        </Form.Item>
        <Form.List name="details">
            {(fields, { add, remove }) => (
                <>
                    {fields.map(({ key, name, fieldKey, ...restField }, index) => (
                        <Space key={key} align="baseline">
                            <Row className="item-materials-row">
                                <Col span={24}>
                                    <Form.Item
                                        label="使用部门"
                                        name={[name, 'department']}
                                        fieldKey={[fieldKey, 'department']}
                                        rules={[{ required: true, message: '请选择部门！' }]}
                                    >
                                        <Select >
                                            {
                                                departmentList.map(item => <Option value={item.id} key={item.id}>{item.name}</Option>)
                                            }
                                        </Select>
                                    </Form.Item>
                                </Col>
                                <Col span={24}>
                                    <Form.Item
                                        label="规格"
                                        name={[name, 'model']}
                                        fieldKey={[fieldKey, 'model']}
                                        rules={[{ required: true, message: '请填写规格！' }]}
                                    >
                                        <Input />
                                    </Form.Item>
                                </Col>
                                <Col span={24}>
                                    <Form.Item
                                        label="物品名称"
                                        name={[name, 'itemName']}
                                        fieldKey={[fieldKey, 'itemName']}
                                        rules={[{ required: true, message: '请填写物品名称！' }]}
                                    >
                                        <Input />
                                    </Form.Item>
                                </Col>
                                <Col span={24}>
                                    <Form.Item
                                        label="单价（元）"
                                        name={[name, 'price']}
                                        fieldKey={[fieldKey, 'price']}
                                        rules={[{ required: true, message: '请填写单价！' }]}
                                    >
                                        <InputNumber onChange={value => handlePrice(value, key)} />
                                    </Form.Item>
                                </Col>
                                <Col span={24}>
                                    <Form.Item
                                        label="数量"
                                        name={[name, 'itemCount']}
                                        fieldKey={[fieldKey, 'itemCount']}
                                        rules={[{ required: true, message: '请填写数量！' }]}
                                    >
                                        <InputNumber onChange={value => handleNumber(value, key)} />
                                    </Form.Item>
                                </Col>
                                <Col span={24}>
                                    <Form.Item
                                        label="总价（元）"
                                    >
                                        <InputNumber value={allMoney[key]} disabled />
                                    </Form.Item>
                                </Col>
                            </Row>
                            <MinusCircleOutlined onClick={() => remove(name)} />
                        </Space>
                    ))}

                    <Form.Item {...tailLayout} className="item-materials-button">
                        <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                            添加购买物品
                        </Button>
                    </Form.Item>
                </>
            )}
        </Form.List>

        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit" loading={buttonLoading}>
                提交申请
            </Button>
        </Form.Item>
    </Form>
}
const tailLayout = {
    wrapperCol: { offset: 0, span: 24 },
};

export default WordOffice